<!-- 个体工商户 -->
<template>
    <div class="individualBusiness">
        <div v-if="employedList.length > 0">
            <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
                <van-list
                    v-model:loading="loading"
                    :finished="finished"
                    finished-text="没有更多了"
                    @load="onLoad"
                >
                    <div class="item" @click="goDetail(item)" v-for="item in employedList" :key="item.id">
                        <div class="itemHead flex alignCenter justifyBetween">
                            <div class="updateTime" style="color: #333333;">{{item.updateTime}}</div>
                            <div :class="'state'+item.state">{{employedStateFilter(item.state)}}</div>
                        </div>
                        <div class="flex alignCenter justifyBetween">
                            <div>
                                <div class="laborCompanyName">{{item.laborCompanyName}}</div>
                                <div class="industrialParkName">{{item.industrialParkName}}</div>
                            </div>
                            <van-icon name="arrow" color="#666666"/>
                        </div>
                    </div>
                </van-list>
            </van-pull-refresh>
        </div>
        <Empty v-else />
        <div class="btm">
            <van-button @click="getLaborHasIndustrialList" type="primary" block>新增</van-button>
        </div>
    </div>

    <van-popup
        v-model:show="show"
        position="bottom"
        >
        <van-cascader
            v-if="show"
            v-model="cascaderValue"
            title="请选择企业园区"
            :options="options"
            @change="onChange"
        />
    </van-popup>
</template>

<script>
import { ref, reactive, getCurrentInstance } from 'vue';
import Empty from '@/components/Empty';
import { Button , Popup , Cascader , Icon , List , PullRefresh } from 'vant';
import storage from 'store'
import { ACCESS_TOKEN } from '@/utils/types'
export default {
    components: {
        Empty,
        [Button.name]: Button,
        [Popup.name]: Popup,
        [Cascader.name]: Cascader,
        [Icon.name]: Icon,
        [List.name]: List,
        [PullRefresh.name]: PullRefresh,
    },
    setup() {
        const { proxy } = getCurrentInstance();

        const token = proxy.getHashParam('token');
        storage.set(ACCESS_TOKEN,token);

        const assetsAddress = proxy.assetsAddress;

        // 下拉刷新，上拉加载
        const refreshing = ref(false);
        const loading = ref(false);
        const finished = ref(false);
        const onRefresh = () => {
            setTimeout(() => {
                finished.value = false;
                refreshing.value = true;
                onLoad();
            }, 1000);
        };
        const onLoad = () => {
            if (refreshing.value) {
                page.value = 1;
                employedList.value = [];
            }
            getSelfEmployedList()
        };

        // 获取个体工商户申请列表
        const page = ref(1);
        const employedList = ref([]);
        const getSelfEmployedList = () => {
            proxy.$http.industrialApi.getSelfEmployedList({page: page.value})
            .then(res => {
                if(res.success){
                    if(page.value == 1){
                        employedList.value = res.data;
                    }else{
                        employedList.value = employedList.value.concat(res.data);
                    }
                    page.value++;
                    loading.value = false;
                    refreshing.value = false;
                    if(page.value * 10 >= res.totalCount){
                        finished.value = true;
                    }
                }else{
                    proxy.showToast({message: res.errMessage});
                }
            })
        }
        getSelfEmployedList();

        // 跳转详情
        const goDetail = (item) => {
            proxy.$router.push({name: 'individualBusinessDetail',params: {'item': JSON.stringify(item)}});
        }

        // POPUP弹框
        const show = ref(false);
        const showPopup = () => {
            show.value = true;
        };
        // 获取劳务企业列表
        const industry = ref(''); // 行业名称
        const laborCompanyId = ref(''); // 劳务公司ID
        const laborCompany = ref(''); // 劳务公司名称
        const options = ref([]);
        const cascaderValue = ref('');
        const getLaborHasIndustrialList = () => {
            proxy.$http.industrialApi.laborHasIndustrialList()
            .then(res => {
                if(res.success){
                    let list = [];
                    for (let index = 0; index < res.data.length; index++) {
                        const element = res.data[index];
                        element['value'] = element.id;
                        element['text'] = element.companyName;
                        list.push(element);
                    }
                    options.value = list;
                    showPopup();
                }else{
                    proxy.showToast({message: res.errMessage});
                }
            })
        }
        // 获取劳务公司下园区列表
        const getLaborIndustryList = (laborCompanyId) => {
            return new Promise((resolve,reject) => {
                proxy.$http.industrialApi.laborIndustryList({laborCompanyId:laborCompanyId})
                .then(res => {
                    if(res.success){
                        var arr = [];
                        for (let index = 0; index < res.data.length; index++) {
                            const item = res.data[index];
                            var obj = {
                                'value': item,
                                'text': item,
                            }
                            arr.push(obj);
                        }
                        resolve(arr)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        }
        // 查询是否和劳务公司签约
        const _appletSelfEmployedStatus = ({laborCompanyId}) => {
            return new Promise((resolve,reject) => {
                proxy.$http.industrialApi.appletSelfEmployedStatus({LaborCompanyId: laborCompanyId})
                .then(res => {
                    console.log(res,'res')
                    if(res.success){
                        resolve(res.data);
                    }else{
                        wx.showToast({
                        title: res.errMessage,
                        icon: 'none',
                        })
                    }
                })
            })
        }
        // 切换园区信息
        const onChange = async({value,tabIndex}) => {
            console.log(value,'value',tabIndex)
            if(tabIndex == 0){
                try {
                    let laborCompany = options.value.find(item => item.id == value);
                    var appletStatus = await _appletSelfEmployedStatus({laborCompanyId: value});
                    if(!appletStatus && laborCompany.industrialParkRegisterType == '2'){
                        proxy.showDialog({
                            message: '请先承接该公司下的任务，并完成合同签署后，方可申请注册个体工商户',
                            showCancelButton: false,
                        })
                        return;
                    }
                    var children = await getLaborIndustryList(value);
                    console.log(children,'children')
                    var index = options.value.findIndex(item => item.id == value);
                    var opt = options.value;
                    opt[index].children = children;
                    options.value = opt;
                    laborCompanyId.value = value;
                } catch (error) {
                    proxy.showToast({message: error});
                }
            }else{
                industry.value = value;
                proxy.$router.push({name: 'industrialParkDetail',params: {'laborCompanyId': JSON.stringify(laborCompanyId.value),'industry': encodeURIComponent(JSON.stringify(industry.value)),'isAdd': '1'}})
            }
        }

        return {
            assetsAddress,
            employedList,
            show,
            showPopup,
            options,
            cascaderValue,
            getLaborHasIndustrialList,
            onChange,
            refreshing,
            onRefresh,
            loading,
            finished,
            onLoad,
            goDetail,
        }
    }
}

</script>
<style scoped>
.individualBusiness{
    padding-bottom: 120px;
}
.btm{
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
}

.item{
    margin: 5px 12px;
    border-radius: 5px;
    background: #FFFFFF;
    padding: 0 12px 12px;
}
.itemHead{
    height: 40px;
    font-size: 14px;
}
.laborCompanyName{
    font-size: 15px;
    margin-bottom: 5px;
}
.industrialParkName{
    font-size: 13px;
    color: #666666;
}

/* 状态 */
.state1{
    color: orange;
}
.state2{
    color: green;
}
.state3{
    color: red;
}
</style>